﻿using System;
using System.Threading;

namespace LockDemo
{
    class Account
    {
        int balance;
        Random r = new Random();
        public Account(int initial)
        {
            balance = initial;
        }

        int Withdraw(int amount)
        {

            // This condition will never be true unless the lock statement  
            // is commented out:  
            if (balance < 0)
                throw new Exception("Negative Balance");

            // Comment out the next line to see the effect of leaving out   
            // the lock keyword:  
            lock (this)
            {
                if (balance >= amount)
                {
                    Console.WriteLine("提款窗口:  " + Thread.CurrentThread.Name);
                    Console.WriteLine("提款之前余额(Balance before Withdrawal):  " + balance);
                    Console.WriteLine("提款数量(Amount to Withdraw)           : -" + amount);
                    balance = balance - amount;
                    Console.WriteLine("提款之后余额(Balance after Withdrawal) :  " + balance);
                    Console.WriteLine();
                    return amount;
                }
                else return 0; // transaction rejected  
            }
        }

        public void DoTransactions()
        {
            //模拟100个人来提款，每次提1-30元  
            for (int i = 0; i < 100; i++)
                Withdraw(r.Next(1, 30));
        }
    }
    class Test
    {
        public static void Main22()
        {
            Thread[] threads = new Thread[5];

            //总额为100元  
            Account acc = new Account(100);

            //定义并初始化5个线程，模拟银行的5个窗口  
            for (int i = 0; i < 5; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions)) { Name = i + "号" };
                threads[i] = t;
            }

            //启动5个线程，模拟银行的5个窗口开始工作  
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("threads[{0}].Start()", i);
                threads[i].Start();
            }
            Console.Read();
        }
    }
}
